import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Button, Drawer, FloatButton, Form, Input, InputRef, List, message, Modal, Popover, Tooltip } from "antd";
import UglyAvatar from "@/components/UglyAvatar";
import { DeleteFilled, EditOutlined, ExclamationCircleFilled, PlusOutlined, RedoOutlined } from "@ant-design/icons";
import { deleteDialog, editDialog, getDialogList, updateUserInfo } from "@/api/modules/gpt";
import { Gpt } from "@/api/interface";
import type { SearchProps } from 'antd/es/input/Search';
import ModalFaceback from "./ModalFaceback";
const userDatas = ["月之两面", "用户反馈", "退出登录"]

interface Props {
    userInfo: Gpt.UserInfo,
    ref: any;
    onDialogOpt?: (_userInfo: Gpt.DialogItem) => void;
    onCreateDialog?: () => Promise<void>
}

const PageChild: React.FC<Props> = forwardRef((props, ref) => {

    const [drawerOpen, setDrawerOpen] = useState(false);
    const [modalOpen, setModalOpen] = useState(false);
    const [avatarLoading, setAvatarLoading] = useState(false)
    const [chatList, setChatList] = useState<Gpt.DialogList>()
    const uglyRef = useRef<UglyRef>(null);
    const titleRef = useRef<InputRef>(null);
    const modalFacebackRef = useRef<ModalFacebackRef>(null);
    const [form] = Form.useForm();
    const [activeDialogId, setActiveDialogId] = useState("")

    useImperativeHandle(ref, () => ({
        chatList,
        setChatList,
        setDrawerOpen
    }))
    useEffect(() => {
        // last_dialog_id改变时自动获取回话列表
        if (props.userInfo.last_dialog_id) {
            if (activeDialogId === props.userInfo.last_dialog_id) {
                return
            }

            getDialogList().then(res => {
                setActiveDialogId(props.userInfo.last_dialog_id)
                setChatList(() => res.data)
                setTimeout(async () => {
                    const activeItem = res.data.list.find(item => item._id === props.userInfo.last_dialog_id)
                    if (activeItem) {
                        props.onDialogOpt?.(activeItem!)
                    } else {
                        await props.onCreateDialog?.()
                        message.success("检测到该会话不存在，已为您创建新会话")
                    }
                });
            })
        }
    }, [props.userInfo.last_dialog_id])



    const getDialogListData = async () => {
        const res = await getDialogList()
        setChatList(res.data)
    }
    const updateAvatar = async () => {
        setAvatarLoading(true)
        uglyRef.current!.generateFace()

        setTimeout(async () => {
            const blob = new Blob([uglyRef.current!.dom!.outerHTML], { type: 'image/svg' });
            console.log(uglyRef.current!.dom!.outerHTML);

            const formdata = new FormData()
            formdata.append("file", blob)
            formdata.append("fileName", props.userInfo._id + ".svg")
            await updateUserInfo(formdata)
            setAvatarLoading(false)
        });

    }

    // 会话操作
    // 会话表单提交
    const onDialogFinish = async () => {
        console.log(form.getFieldsValue());
        const id = form.getFieldValue("_id")
        const title = form.getFieldValue("title")
        await editDialog(id, title)
        await getDialogListData()
        setModalOpen(false)
        message.success("会话编辑成功");


    }

    const searchDialog: SearchProps['onSearch'] = (value) => {
        console.log(value)
    };

    const onDialogDel = (item: Gpt.DialogItem, e: React.MouseEvent<HTMLElement, MouseEvent>) => {
        e.stopPropagation()
        Modal.confirm({
            mask: false,
            title: "删除",
            content: `确定是否删除【${item.title}】`,
            icon: <ExclamationCircleFilled />,
            onOk() {
                deleteDialog(item._id).then(res => {
                    getDialogListData()
                    message.success(`【${item.title}】已被删除`);
                });
            },
            onCancel() {
                message.warning('已取消');
            }
        });
    }
    const onDialogEdit = (item: Gpt.DialogItem, e: React.MouseEvent<HTMLElement, MouseEvent>) => {
        e.stopPropagation()
        setModalOpen(true)
        form.setFieldsValue(item)
        setTimeout(() => {
            titleRef.current?.focus()
        });
    }
    const onClickDialogItem = (item: Gpt.DialogItem) => {
        setActiveDialogId(item._id)
        if (props.userInfo.last_dialog_id === item._id) {
            return
        }
        props.onDialogOpt?.(item)
        setDrawerOpen(false)

    }
    const userOpt = (index: number) => {
        if (index === 1) {
            modalFacebackRef.current?.setModalOpen(true)
        }

    }

    return (
        < >
            <FloatButton onClick={() => setDrawerOpen(true)} />
            <Drawer getContainer=".only_gpt" open={drawerOpen} onClose={() => setDrawerOpen(false)}>
                <div className="drawer_center">
                    <Popover placement="bottom" trigger="click" title="手机号" content={<List
                        dataSource={userDatas}
                        renderItem={(label, index) => (
                            <List.Item style={{ cursor: "pointer" }} onClick={() => userOpt(index)}>
                                {label}
                            </List.Item>
                        )}
                    />} arrow={false}>
                        <div className="avatar">
                            <UglyAvatar ref={uglyRef} src={props.userInfo.avatar} />
                            <Button type="text" size="small" icon={<RedoOutlined />} onClick={updateAvatar} disabled={avatarLoading} loading={avatarLoading} />
                        </div>
                        <div className="username">{props.userInfo.name}</div>
                    </Popover>
                    <List
                        header={<Input.Search placeholder="搜索历史记录" onSearch={searchDialog} addonBefore={<Tooltip title="新建会话"><PlusOutlined style={{ cursor: "pointer" }} onClick={props.onCreateDialog} /></Tooltip>} allowClear />}
                        className="chat_list"
                        dataSource={chatList?.list}
                        renderItem={(item) => (
                            <List.Item onClick={(e) => onClickDialogItem(item)} actions={[<Button size="small" onClick={e => onDialogEdit(item, e)} icon={<EditOutlined />} />, <Button size="small" onClick={e => onDialogDel(item, e)} icon={<DeleteFilled />} danger />]} className={activeDialogId == item._id ? "ant_list_active" : undefined}>
                                <List.Item.Meta
                                    title={item.title}
                                    description={item.updated_date}
                                />
                            </List.Item>
                        )}
                    />
                </div>
            </Drawer>

            <Modal title={`会话编辑`} open={modalOpen} onCancel={() => setModalOpen(false)} onOk={() => form.submit()} okText="提交">
                <Form
                    form={form}
                    onFinish={onDialogFinish}
                >
                    <Form.Item
                        name="_id"
                        hidden
                    >
                        <Input />
                    </Form.Item>
                    <Form.Item
                        name="title"
                        rules={[{ required: true, message: '请输入会话名称' }]}
                    >
                        <Input ref={titleRef} placeholder="请输入会话名称" />
                    </Form.Item>
                </Form>
            </Modal>
            <ModalFaceback ref={modalFacebackRef} />
        </>
    );

})
    ;

export default PageChild;
